package cs241.lab.array;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Random;

import cs241.lab.names.Names;

public class ScoreArray {
	
	private GameScore [] gameScores;
	
	public ScoreArray(int numberOfScores){
		
		this.generateScores(numberOfScores);
		
	}
	
	public void generateScores(int numberOfScores){
		
		GameScore score;
		gameScores = new GameScore[numberOfScores];
		Random random = new Random();
		
		for(int i = 0; i < gameScores.length; i++){
			String name = Names.Names[random.nextInt(Names.Names.length)];
			score = new GameScore(name, random.nextInt(100));
			gameScores[i] = score;
		}
		
		gameScores = this.sort(gameScores);
	}
	
	public void addScore(String name, int score){
		GameScore newScore = new GameScore(name, score);
		this.add(newScore);		
	}
	
	public void addScore (GameScore score){
		this.add(score);
	}
	
	private void add(GameScore newScore){
		
		GameScore [] temp = new GameScore[gameScores.length + 1];
		
		for(int i = 0; i < gameScores.length; i++){
			temp[i] = gameScores[i];
		}
		
		temp[temp.length - 1] = newScore;
		
		gameScores = this.sort(temp);
		
	}
	
	private GameScore [] sort(GameScore [] scores) {

		int n = scores.length;

		for (int i = 1; i < n; i++) { // index from the second character in a

			GameScore cur = scores[i]; // the current character to be inserted

			int j = i - 1; // start comparing with cell left of i

			while ((j >= 0) && (scores[j].getScore() > cur.getScore())){ // while a[j] is out of order with cur

				scores[j + 1] = scores[j--]; // move a[j] right and decrement j

				scores[j + 1] = cur; // this is the proper place for cur

			}
		}
		
		return scores;
	}
	
	public void printScores(){
		
		for(int i = 0; i < gameScores.length; i++){
			System.out.print("Name: " + gameScores[i].getName());
			System.out.print(" ");
			System.out.print("Score: " + gameScores[i].getScore());
			System.out.println();
			System.out.println();
		}
		
	}
	
}
